package com.supreme.simpleserver.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * 定义Aspect切面拦截自定义SimpleTransaction
 */
@Aspect
@Component
@Slf4j
public class TransactionAspect {

    private final DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    public TransactionAspect(DataSourceTransactionManager dataSourceTransactionManager) {
        this.dataSourceTransactionManager = dataSourceTransactionManager;
    }

    /**
     * 自定义事务
     * @param proceedingJoinPoint
     * @return
     */
    @Around(value = "@annotation(com.supreme.simpleserver.annotation.SimpleTransactional)")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {
        TransactionStatus transaction = null;
        Object object = null;
        try {
            log.info("==========> 开启事务");
            transaction = this.dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());

            log.info("==========> 目标方法");
            object = proceedingJoinPoint.proceed();

            log.info("==========> 提交事务: {}", transaction);
            this.dataSourceTransactionManager.commit(transaction);
        } catch (Throwable throwable) {
            throwable.printStackTrace();

            log.info("==========> 回滚事务: {}", transaction);
            if (transaction != null) {
                this.dataSourceTransactionManager.rollback(transaction);
            }
        }

        return object;
    }
}
